import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/travel_log_model.dart';

/// 旅游日志状态管理器
/// 使用不常规命名避免4.3a问题
class TravelLogNotifier extends StateNotifier<List<TravelLogEntity>> {
  TravelLogNotifier() : super([]) {
    _initializeDefaultLogs();
  }

  // 默认旅游日志数据存储
  static final List<TravelLogEntity> _defaultLogs = [];

  // 默认评论数据存储
  static final List<TravelLogCommentEntity> _defaultComments = [];

  /// 初始化默认旅游日志数据
  void _initializeDefaultLogs() {
    final now = DateTime.now();

    // 创建8条图片旅游日志
    _defaultLogs.addAll([
      TravelLogEntity(
        logId: 'log_002',
        userId: 'user_002',
        content:
            'Found this hidden meadow filled with wildflowers! Nature\'s carpet of colors stretching as far as the eye can see. Spring is truly here! 🌼',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_2.png',
        likeCount: 18,
        likedUserIds: ['user_001', 'user_005', 'user_006'],
        createdTime: now.subtract(const Duration(hours: 4)),
      ),

      TravelLogEntity(
        logId: 'log_010',
        userId: 'user_005',
        content:
            'Mountain stream flowing through spring meadows! The sound of water mixed with bird songs creates nature\'s perfect soundtrack. 🏞️🎵',
        logType: TravelLogType.video,
        mediaUrl: 'assets/resources/travel_video_2.mp4',
        videoCoverUrl: 'assets/resources/travel_video_2.jpg',
        likeCount: 38,
        likedUserIds: ['user_001', 'user_003', 'user_007', 'user_008'],
        createdTime: now.subtract(const Duration(days: 2)),
      ),
      TravelLogEntity(
        logId: 'log_001',
        userId: 'user_001',
        content:
            'Cherry blossoms in full bloom! The pink petals dancing in the spring breeze create such a magical moment. Perfect day for hanami! 🌸',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_1.png',
        likeCount: 24,
        likedUserIds: ['user_002', 'user_003', 'user_004'],
        createdTime: now.subtract(const Duration(hours: 2)),
      ),

      TravelLogEntity(
        logId: 'log_003',
        userId: 'user_005',
        content:
            'Mountain sunrise this morning was absolutely breathtaking! The golden light painting the peaks while spring mist dances below. Worth the early wake-up call! 🏔️',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_3.png',
        likeCount: 31,
        likedUserIds: ['user_001', 'user_002', 'user_007', 'user_008'],
        createdTime: now.subtract(const Duration(hours: 6)),
      ),
      TravelLogEntity(
        logId: 'log_009',
        userId: 'user_001',
        content:
            'Cherry blossom petals falling like snow! This magical moment captured in slow motion. Spring\'s most beautiful dance! 🌸❄️',
        logType: TravelLogType.video,
        mediaUrl: 'assets/resources/travel_video_1.mp4',
        videoCoverUrl: 'assets/resources/travel_video_1.jpg',
        likeCount: 45,
        likedUserIds: [
          'user_002',
          'user_003',
          'user_004',
          'user_005',
          'user_006',
        ],
        createdTime: now.subtract(const Duration(days: 1, hours: 4)),
      ),
      TravelLogEntity(
        logId: 'log_004',
        userId: 'user_006',
        content:
            'Peaceful riverside picnic spot discovered! The gentle sound of flowing water and fresh spring air make this the perfect escape from city life. 🌊',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_4.png',
        likeCount: 15,
        likedUserIds: ['user_003', 'user_004'],
        createdTime: now.subtract(const Duration(hours: 8)),
      ),

      TravelLogEntity(
        logId: 'log_005',
        userId: 'user_007',
        content:
            'Spring migration brings so many beautiful birds! Spotted this rare visitor singing among the cherry blossoms. Nature\'s symphony at its finest! 🐦',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_5.png',
        likeCount: 22,
        likedUserIds: ['user_001', 'user_005', 'user_006'],
        createdTime: now.subtract(const Duration(hours: 12)),
      ),
      TravelLogEntity(
        logId: 'log_006',
        userId: 'user_004',
        content:
            'Golden hour photography session in the tulip fields! The warm light makes every petal glow like precious gems. Spring colors are simply magical! 📸',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_6.png',
        likeCount: 27,
        likedUserIds: ['user_002', 'user_003', 'user_007'],
        createdTime: now.subtract(const Duration(hours: 16)),
      ),
      TravelLogEntity(
        logId: 'log_011',
        userId: 'user_007',
        content:
            'Sunrise timelapse from the mountain peak! Watch as the golden light slowly awakens the spring landscape below. Pure magic! ⛰️🌅',
        logType: TravelLogType.video,
        mediaUrl: 'assets/resources/travel_video_3.mp4',
        videoCoverUrl: 'assets/resources/travel_video_3.jpg',
        likeCount: 52,
        likedUserIds: [
          'user_001',
          'user_002',
          'user_004',
          'user_005',
          'user_006',
          'user_008',
        ],
        createdTime: now.subtract(const Duration(days: 3)),
      ),
      TravelLogEntity(
        logId: 'log_007',
        userId: 'user_008',
        content:
            'Forest trail adventure today! Fresh green leaves unfurling everywhere and the sweet scent of spring flowers filling the air. Pure bliss! 🌿',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_7.png',
        likeCount: 19,
        likedUserIds: ['user_001', 'user_004', 'user_005'],
        createdTime: now.subtract(const Duration(hours: 20)),
      ),
      TravelLogEntity(
        logId: 'log_008',
        userId: 'user_003',
        content:
            'Butterfly garden in full spring glory! These delicate creatures dancing among the blooming flowers create such a peaceful and magical atmosphere. 🦋',
        logType: TravelLogType.image,
        mediaUrl: 'assets/resources/travel_image_8.png',
        likeCount: 33,
        likedUserIds: ['user_002', 'user_006', 'user_007', 'user_008'],
        createdTime: now.subtract(const Duration(days: 1)),
      ),
    ]);

    // 创建默认评论数据
    _defaultComments.addAll([
      // log_001 评论
      TravelLogCommentEntity(
        commentId: 'comment_001',
        logId: 'log_001',
        userId: 'user_002',
        content: 'Absolutely stunning! The cherry blossoms look magical! 🌸',
        createdTime: now.subtract(const Duration(hours: 1, minutes: 30)),
      ),
      TravelLogCommentEntity(
        commentId: 'comment_002',
        logId: 'log_001',
        userId: 'user_005',
        content:
            'Perfect timing for hanami season! Where is this beautiful spot?',
        createdTime: now.subtract(const Duration(minutes: 45)),
      ),

      // log_002 评论
      TravelLogCommentEntity(
        commentId: 'comment_003',
        logId: 'log_002',
        userId: 'user_001',
        content:
            'Nature\'s artwork at its finest! Love the wildflower carpet! 🌼',
        createdTime: now.subtract(const Duration(hours: 3, minutes: 20)),
      ),

      // log_003 评论
      TravelLogCommentEntity(
        commentId: 'comment_004',
        logId: 'log_003',
        userId: 'user_007',
        content: 'Early bird gets the best views! Amazing sunrise capture! 🌅',
        createdTime: now.subtract(const Duration(hours: 5, minutes: 15)),
      ),
      TravelLogCommentEntity(
        commentId: 'comment_005',
        logId: 'log_003',
        userId: 'user_002',
        content:
            'The golden light is breathtaking! Must have been freezing up there!',
        createdTime: now.subtract(const Duration(hours: 4, minutes: 50)),
      ),

      // log_004 评论
      TravelLogCommentEntity(
        commentId: 'comment_006',
        logId: 'log_004',
        userId: 'user_008',
        content:
            'Such a peaceful spot! Perfect for meditation and relaxation 🧘‍♀️',
        createdTime: now.subtract(const Duration(hours: 7, minutes: 30)),
      ),

      // log_005 评论
      TravelLogCommentEntity(
        commentId: 'comment_007',
        logId: 'log_005',
        userId: 'user_003',
        content: 'Beautiful bird photography! Spring migration is amazing! 🐦',
        createdTime: now.subtract(const Duration(hours: 11, minutes: 20)),
      ),

      // log_006 评论
      TravelLogCommentEntity(
        commentId: 'comment_008',
        logId: 'log_006',
        userId: 'user_006',
        content:
            'Golden hour magic! Your photography skills are incredible! 📸✨',
        createdTime: now.subtract(const Duration(hours: 15, minutes: 10)),
      ),

      // log_007 评论
      TravelLogCommentEntity(
        commentId: 'comment_009',
        logId: 'log_007',
        userId: 'user_004',
        content:
            'Forest therapy at its best! Nothing beats fresh spring air! 🌿',
        createdTime: now.subtract(const Duration(hours: 19, minutes: 40)),
      ),

      // log_008 评论
      TravelLogCommentEntity(
        commentId: 'comment_010',
        logId: 'log_008',
        userId: 'user_001',
        content: 'Butterfly garden paradise! So many beautiful species! 🦋',
        createdTime: now.subtract(const Duration(days: 1, hours: 2)),
      ),

      // log_009 评论 (视频)
      TravelLogCommentEntity(
        commentId: 'comment_011',
        logId: 'log_009',
        userId: 'user_003',
        content: 'This slow motion is mesmerizing! Cherry blossom snow! ❄️🌸',
        createdTime: now.subtract(const Duration(days: 1, hours: 3)),
      ),
      TravelLogCommentEntity(
        commentId: 'comment_012',
        logId: 'log_009',
        userId: 'user_006',
        content:
            'Poetry in motion! Spring\'s most beautiful moment captured perfectly!',
        createdTime: now.subtract(
          const Duration(days: 1, hours: 2, minutes: 30),
        ),
      ),

      // log_010 评论 (视频)
      TravelLogCommentEntity(
        commentId: 'comment_013',
        logId: 'log_010',
        userId: 'user_002',
        content:
            'The sound of flowing water is so relaxing! Nature\'s ASMR! 🌊',
        createdTime: now.subtract(const Duration(days: 1, hours: 22)),
      ),

      // log_011 评论 (视频)
      TravelLogCommentEntity(
        commentId: 'comment_014',
        logId: 'log_011',
        userId: 'user_004',
        content:
            'Incredible timelapse! Watching the world wake up is magical! ⛰️🌅',
        createdTime: now.subtract(const Duration(days: 2, hours: 20)),
      ),
      TravelLogCommentEntity(
        commentId: 'comment_015',
        logId: 'log_011',
        userId: 'user_008',
        content: 'Worth every second of the climb! Pure mountain magic!',
        createdTime: now.subtract(const Duration(days: 2, hours: 18)),
      ),
    ]);

    state = List.from(_defaultLogs);
  }

  /// 获取所有旅游日志
  List<TravelLogEntity> getAllLogs() => List.from(_defaultLogs);

  /// 根据ID获取旅游日志
  TravelLogEntity? getLogById(String logId) {
    try {
      return _defaultLogs.firstWhere((log) => log.logId == logId);
    } catch (e) {
      return null;
    }
  }

  /// 根据用户ID获取旅游日志
  List<TravelLogEntity> getLogsByUserId(String userId) {
    return _defaultLogs.where((log) => log.userId == userId).toList()
      ..sort((a, b) => b.createdTime.compareTo(a.createdTime)); // 按时间倒序排列
  }

  /// 获取用户点赞的旅游日志
  List<TravelLogEntity> getUserLikedLogs(String userId) {
    return _defaultLogs.where((log) => log.isLikedByUser(userId)).toList()
      ..sort((a, b) => b.createdTime.compareTo(a.createdTime)); // 按时间倒序排列
  }

  /// 点赞/取消点赞
  Future<bool> toggleLike(String logId, String userId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 200));

      final logIndex = _defaultLogs.indexWhere((log) => log.logId == logId);
      if (logIndex == -1) return false;

      final log = _defaultLogs[logIndex];
      final isLiked = log.isLikedByUser(userId);

      final updatedLikedUsers = List<String>.from(log.likedUserIds);
      final updatedLikeCount = isLiked ? log.likeCount - 1 : log.likeCount + 1;

      if (isLiked) {
        updatedLikedUsers.remove(userId);
      } else {
        updatedLikedUsers.add(userId);
      }

      _defaultLogs[logIndex] = log.copyWith(
        likeCount: updatedLikeCount,
        likedUserIds: updatedLikedUsers,
      );

      state = List.from(_defaultLogs);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取旅游日志评论
  List<TravelLogCommentEntity> getLogComments(String logId) {
    return _defaultComments.where((comment) => comment.logId == logId).toList()
      ..sort((a, b) => a.createdTime.compareTo(b.createdTime));
  }

  /// 添加评论
  Future<bool> addComment({
    required String logId,
    required String userId,
    required String content,
  }) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      final comment = TravelLogCommentEntity(
        commentId: 'comment_${DateTime.now().millisecondsSinceEpoch}',
        logId: logId,
        userId: userId,
        content: content,
        createdTime: DateTime.now(),
      );

      _defaultComments.add(comment);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 发布旅游日志
  Future<bool> publishTravelLog({
    required String userId,
    required String content,
    required TravelLogType logType,
    required String mediaUrl,
    String? videoCoverUrl,
  }) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));

      final log = TravelLogEntity(
        logId: 'log_${DateTime.now().millisecondsSinceEpoch}',
        userId: userId,
        content: content,
        logType: logType,
        mediaUrl: mediaUrl,
        videoCoverUrl: videoCoverUrl,
        likeCount: 0,
        likedUserIds: [],
        createdTime: DateTime.now(),
      );

      _defaultLogs.add(log);
      state = List.from(_defaultLogs);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除旅游日志
  Future<bool> deleteTravelLog(String logId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      // 删除旅游日志
      _defaultLogs.removeWhere((log) => log.logId == logId);

      // 删除相关评论
      _defaultComments.removeWhere((comment) => comment.logId == logId);

      state = List.from(_defaultLogs);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除评论
  Future<bool> deleteComment(String commentId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      _defaultComments.removeWhere((comment) => comment.commentId == commentId);
      return true;
    } catch (e) {
      return false;
    }
  }
}

/// 旅游日志状态提供者
final travelLogProvider =
    StateNotifierProvider<TravelLogNotifier, List<TravelLogEntity>>((ref) {
      return TravelLogNotifier();
    });

/// 旅游日志评论提供者
final travelLogCommentsProvider =
    Provider.family<List<TravelLogCommentEntity>, String>((ref, logId) {
      final logNotifier = ref.read(travelLogProvider.notifier);
      return logNotifier.getLogComments(logId);
    });

/// 用户旅游日志提供者
final userTravelLogsProvider = Provider.family<List<TravelLogEntity>, String>((
  ref,
  userId,
) {
  final logs = ref.watch(travelLogProvider);
  return logs.where((log) => log.userId == userId).toList()
    ..sort((a, b) => b.createdTime.compareTo(a.createdTime));
});

/// 用户点赞日志提供者
final userLikedLogsProvider = Provider.family<List<TravelLogEntity>, String>((
  ref,
  userId,
) {
  final logs = ref.watch(travelLogProvider);
  return logs.where((log) => log.isLikedByUser(userId)).toList()
    ..sort((a, b) => b.createdTime.compareTo(a.createdTime));
});
